package com.song.sparkstudy.stream;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaPairInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;

import kafka.serializer.StringDecoder;
import scala.Tuple2;

public class KafkaDirectWordCount {
	
	/**
	 *    每隔两秒中 进行一次计算 从kafka 中取出数据，然后转换
	 * @param args
	 */
	
	public static void main(String[] args) {
		SparkConf conf = new SparkConf().setAppName("kafka word count");
		
		JavaStreamingContext context =  new JavaStreamingContext(conf ,Durations.seconds(20));
		
		HashSet<String> topics = new HashSet<>(Arrays.asList("song","test"));
		HashMap<String, String> kafkaparam = new HashMap<>();
		kafkaparam.put("metadata.broker.list", "song-dinfo:9092");
		kafkaparam.put("auto.offset.reset", "smallest");
		
		JavaPairInputDStream<String, String> messages =  KafkaUtils.createDirectStream(context, String.class, String.class	, StringDecoder.class, StringDecoder.class, kafkaparam	, topics);
		
		JavaDStream<String> lines =  messages.map(new Function<Tuple2<String,String>, String>() {

			
			public String call(Tuple2<String, String> t) throws Exception {
				
				return t._2;
			}
		});
		
		JavaDStream<String> words   = lines.flatMap(new FlatMapFunction<String, String>() {

			@Override
			public Iterable<String> call(String str) throws Exception {
				// TODO Auto-generated method stub
				return Arrays.asList( str.split(" "));
			}
			
		});
		
		JavaPairDStream<String, Integer> wordcounts = words.mapToPair( new PairFunction<String, String, Integer>() {

			@Override
			public Tuple2<String, Integer> call(String key) throws Exception {
				// TODO Auto-generated method stub
				return new Tuple2<String, Integer>(key, 1);
			}
		} ).reduceByKey(new Function2<Integer, Integer, Integer>() {
			
			@Override
			public Integer call(Integer v1, Integer v2) throws Exception {
				// TODO Auto-generated method stub
				return v1+ v2;
			}
		});
		
		wordcounts.print();
		context.start();
		context.awaitTermination();
	}
	
	
}
 